import Vue from 'vue'
import VueRouter from 'vue-router'
// 一级路由
import Login from '@/views/login'
import Layout from '@/views/layout'
import NotFound from '@/views/404'
import UserEdit from '@/views/layout/user/edit.vue'
import Chat from '@/views/layout/user/chat.vue'
// 二级路由
import Home from '@/views/layout/home'
import User from '@/views/layout/user'
import Video from '@/views/layout/video'
import Wd from '@/views/layout/wd'

// 搜索界面
import Search from '@/views/search'
import SearcResult from '@/views/search/searcResult'

// 新闻
import News from '@/views/news'
import store from '@/store'
Vue.use(VueRouter)
const routes = [
  {
    path: '/',
    component: Layout,
    redirect: '/home',
    children: [
      {
        path: '/home',
        component: Home,
        meta: {
          isKeepLive: true
        }
      },
      {
        path: 'wd',
        component: Wd
      },
      {
        path: 'video',
        component: Video
      },
      {
        path: 'user',
        component: User
      }
    ]
  },
  {
    path: '/user/userEdit',
    component: UserEdit
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/search',
    component: Search
  },
  {
    path: '/search/searcResult',
    component: SearcResult
  },
  {
    path: '/news/:id',
    component: News
  },
  {
    path: '/user/chat',
    component: Chat
  },
  {
    path: '*',
    component: NotFound
  }
]

const router = new VueRouter({
  routes
})

const loginURL = ['/user', '/wd', '/user/userEdit']
router.beforeEach(function (to, from, next) {
  const token = store.state.user.token.token
  if (token) {
    next()
  } else {
    if (loginURL.some((item) => to.path === item)) {
      router.push({
        path: '/login',
        query: {
          back: to.fullPath
        }
      })
    } else {
      next()
    }
  }
})

export default router
